from .id_generator import generate_char_id

def create_character(all_chars, game_name, char_name, char_type, image_path=None):
    """Create a new game character and add it to the collection.
    
    Args:
        all_chars (list): List of existing character dictionaries
        game_name (str): Name of the game
        char_name (str): Name of the character
        char_type (str): Type of the character
        image_path (str, optional): Path to the character's image
        
    Returns:
        list: Updated list of character dictionaries
    """
    # Check if character limit is reached
    if len(all_chars) >= 4:
        print("The number of characters has reached the maximum limit (up to 4), so new characters cannot be added!")
        return all_chars
    
    # Create new character dictionary
    new_char = {
        "id": generate_char_id(),
        "game_name": game_name.strip(),
        "char_name": char_name.strip(),
        "char_type": char_type.strip(),
    }
    
    # Add image path if provided
    if image_path:
        new_char["image_path"] = image_path.strip()
    
    all_chars.append(new_char)
    print(f"Successfully added character: {char_name} (from 《{game_name}》）")
    return all_chars

def delete_character(all_chars, target_id):
    """Delete a character with the specified ID from the collection.
    
    Args:
        all_chars (list): List of character dictionaries
        target_id (str): ID of the character to delete
        
    Returns:
        list: Updated list of character dictionaries
    """
    # Find and delete character
    for i, char in enumerate(all_chars):
        if char["id"] == target_id:
            deleted_char = all_chars.pop(i)
            print(f"Successfully deleted the character: {deleted_char['char_name']} (ID: {target_id})")
            return all_chars
    
    # If character not found
    print(f"Failed to delete! The character with ID '{target_id}' was not found.")
    return all_chars

def edit_character(all_chars, target_id, game_name=None, char_name=None, char_type=None, image_path=None):
    """Edit an existing character in the collection.
    
    Args:
        all_chars (list): List of character dictionaries
        target_id (str): ID of the character to edit
        game_name (str, optional): New game name
        char_name (str, optional): New character name
        char_type (str, optional): New character type
        image_path (str, optional): New image path
        
    Returns:
        tuple: (updated_chars, success, message)
    """
    # Find character to edit
    for char in all_chars:
        if char["id"] == target_id:
            # Update fields only if new values are provided
            if game_name is not None:
                char["game_name"] = game_name.strip()
            if char_name is not None:
                char["char_name"] = char_name.strip()
            if char_type is not None:
                char["char_type"] = char_type.strip()
            if image_path is not None:
                if image_path.strip():
                    char["image_path"] = image_path.strip()
                else:
                    # Remove image path if empty string is provided
                    if "image_path" in char:
                        del char["image_path"]
            print(f"Successfully edited the character: {char['char_name']} (ID: {target_id})")
            return all_chars, True, f"Character edited successfully: {char['char_name']}"
    
    # If character not found
    print(f"Failed to edit! The character with ID '{target_id}' was not found.")
    return all_chars, False, f"Character with ID '{target_id}' not found"
